package com.yifeng.repo.endpoint.security.redis.client;

import lombok.Setter;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;

/**
 * Created by daibing on 2020/2/7.
 */
@Setter
public class JedisClient {
    /**
     * redis://[:password]@host:port/db
     */
    private String uri = "redis://:123456@127.0.0.1:6379/0";
    private int maxTotal = 8;
    private int maxIdle = 8;
    private int minIdle = 0;
    private int maxWaitMillis = 1500;
    private boolean testOnBorrow = true;

    /**
     * Redis主从模式使用JedisPool即可（支撑分布式锁），注意：ShardedJedisPool不支持eval和evalsha函数，当前应该不需要。
     */
    private JedisPool jedisPool;

    public void init() throws URISyntaxException {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setNumTestsPerEvictionRun(1024);
        jedisPoolConfig.setTimeBetweenEvictionRuns(Duration.ofSeconds(30));
        jedisPoolConfig.setMinEvictableIdleTime(Duration.ofSeconds(60));
        jedisPoolConfig.setMinEvictableIdleTime(Duration.ofSeconds(60));
        jedisPoolConfig.setSoftMinEvictableIdleTime(Duration.ofSeconds(10));
        jedisPoolConfig.setMaxWait(Duration.ofMillis(maxWaitMillis));
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestWhileIdle(true);
        jedisPoolConfig.setTestOnReturn(false);
        jedisPoolConfig.setJmxEnabled(true);
        jedisPoolConfig.setBlockWhenExhausted(false);
        jedisPool = new JedisPool(jedisPoolConfig, new URI(uri));
    }

    public void destroy() {
        if (jedisPool == null) {
            return;
        }
        jedisPool.close();
    }

    public Jedis get() {
        if (jedisPool.isClosed()) {
            throw new RuntimeException("Jedis pool is closed!");
        }
        return jedisPool.getResource();
    }

    public void close(Jedis res) {
        if (res == null) {
            return;
        }
        res.close();
    }

}
